package com.ktgj.train.controller;

import java.math.BigDecimal;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.utils.helper.StringHelper;
import com.ktgj.common.log.annotation.NoRepeatSubmit;
import com.ktgj.common.log.annotation.SignatureValidation;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.Customer;
import com.ktgj.pay.api.domain.UnionPayQRCodeResponseApi;
import com.ktgj.train.domain.*;
import com.ktgj.train.domain.InterfaceEntity.*;
import com.ktgj.train.domain.vo.CustomerTrain;
import com.ktgj.train.domain.vo.JourneyTrainOrderVo;
import com.ktgj.train.domain.vo.TrainOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ktgj.common.log.annotation.Log;
import com.ktgj.common.log.enums.BusinessType;
import com.ktgj.train.service.ITrainOrderService;
import com.ktgj.common.core.web.controller.BaseController;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.core.utils.poi.ExcelUtil;
import com.ktgj.common.core.web.page.TableDataInfo;

/**
 * 订单Controller
 * 
 * @author ruoyi
 * @date 2021-11-29
 */
@ControllerAdvice
@RestController
@RequestMapping("/order")
public class TrainOrderController extends BaseController
{
    @Autowired
    private ITrainOrderService trainOrderService;
    @Autowired
    private RemoteCustomerService customerService;

    /**
     * 查询订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TrainOrder trainOrder) {
        startPage();
        List<TrainOrder> list = trainOrderService.selectTrainOrderList(trainOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TrainOrder trainOrder) throws IOException {
        List<TrainOrder> list = trainOrderService.selectTrainOrderList(trainOrder);
        ExcelUtil<TrainOrder> util = new ExcelUtil<TrainOrder>(TrainOrder.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @PostMapping("/getInfo")
    public AjaxResult getInfo(@RequestBody Map<String, Long> map) {
        Long orderid = map.get("orderid");
        return AjaxResult.success(trainOrderService.selectTrainOrderById(orderid));
    }

    /**
     * 新增订单
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TrainOrder trainOrder) {
        return toAjax(trainOrderService.insertTrainOrder(trainOrder));
    }

    /**
     * 修改订单
     */
//    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody TrainOrder trainOrder) {
        return toAjax(trainOrderService.updateTrainOrder(trainOrder));
    }

    @PostMapping("/updateByTrainOrder")
    public AjaxResult updateByTrainOrder(@RequestBody TrainOrderVo trainOrderVo) {
        return toAjax(trainOrderService.updateByTrainOrder(trainOrderVo));
    }

    /**
     * 删除订单
     */
    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderids}")
    public AjaxResult remove(@PathVariable Long[] orderids) {
        return toAjax(trainOrderService.deleteTrainOrderByIds(orderids));
    }

    /**
     * 火车票（退票）
     * */
    @PostMapping("/refundApplication")
    public AjaxResult refundApplication(@RequestBody Map<String, Object> map){
        Long orderid = Long.valueOf(map.get("orderid").toString());
        return AjaxResult.success(trainOrderService.refundApplication(orderid));
    }

    //填写订单
//    @SignatureValidation
    @PostMapping("/fillOrder")
    public AjaxResult fillOrder(HttpServletRequest servletRequest, @RequestBody QueryTrainSeatRequest request) {
        String token = servletRequest.getHeader("token");
        TrainFillOrder trainFillOrder = trainOrderService.fillOrder(token, request);
        if (trainFillOrder != null)
            return AjaxResult.success(trainFillOrder);
        else
            return AjaxResult.error("填写订单失败!");
    }

    //生成订单
//    @SignatureValidation
    @PostMapping("/createOrder")
    public AjaxResult createOrder(HttpServletRequest httpServletRequest, @RequestBody GenerateOrder request) {
        String token = null;
        if (request.customerId == null || request.customerId == 0){
            token = httpServletRequest.getHeader("token");
        }

        Order order;
        try {
            order = trainOrderService.createOrder(token, request);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (order != null) {
            return AjaxResult.success(order);
        } else {
            return AjaxResult.error("生成订单失败！");
        }
    }

    //订单详情列表
    @PostMapping("/queryOrderDetail")
    public AjaxResult queryOrderDetail(@RequestBody Map<String, Object> map) {
        String orderNumber = map.get("orderNumber").toString();
        return AjaxResult.success(trainOrderService.queryOrderDetail(orderNumber));
    }

    //取消订单
    //@SignatureValidation
    @PostMapping("/cancelOrder")
    public AjaxResult cancelOrder(HttpServletRequest servletRequest, @RequestBody TrCancellationOrderRequest request) {
        String token = null;
        if (request.customerId == null || request.customerId == 0){
            token = servletRequest.getHeader("token");
        }

        TrainStayOutTicket ticket = null;
        if (token != null) {
            ticket = trainOrderService.cancelOrder(token, request);
        } else {
            ticket = trainOrderService.cancelOrder(null, request);
        }
        return AjaxResult.success(ticket);
    }

    /**
     * 订单详情
     * @param request
     * @param map
     * @return
     */
    //@SignatureValidation
    @PostMapping("/queryTrainOrder")
    public AjaxResult queryTrainOrder(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String token = request.getHeader("token");
        TrainStayOutTicket ticket = null;
        if (token != null) {
            String orderNumber = String.valueOf(map.get("orderNumber"));
            ticket = trainOrderService.queryTrainOrder(token, orderNumber, 0L);
        } else {
            Long customerId = Long.valueOf(map.get("customerId").toString());
            String orderNumber = String.valueOf(map.get("orderNumber"));
            ticket = trainOrderService.queryTrainOrder(null, orderNumber, customerId);
        }

        return AjaxResult.success(ticket);
    }

    /**
     * 退票申请
     * @param request
     * @param map
     * @return
     */
    //@SignatureValidation
    @PostMapping("/retreat")
    public AjaxResult retreat(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String token = null;
        Long customerId = 0l;
        if (map.get("customerId") != null && !map.get("customerId").equals("")){
            customerId = Long.valueOf(map.get("customerId").toString());
        }
        else {
            token = request.getHeader("token");
        }

        String orderNumber = map.get("orderNumber").toString();
        if (StringHelper.isNullOrEmpty(orderNumber)) {
            return AjaxResult.error("订单编号不能为空！");
        }
        RetreatTicket ticket = null;
        if (token != null) {
            ticket = trainOrderService.retreat(token, null, orderNumber);
        } else {
            ticket = trainOrderService.retreat(null, customerId, orderNumber);
        }
        return AjaxResult.success(ticket);
    }

    /**
     * 发起退票请求
     * @param servletRequest
     * @param request
     * @return
     */
    //@SignatureValidation
    @PostMapping("/retreatTicket")
    public AjaxResult retreatTicket(HttpServletRequest servletRequest, @RequestBody TrRetreatTicketRequest request) {
        if (request.orderNumber != null && !request.orderNumber.equals("") &&
                request.orderItemID != null && request.orderItemID.length > 0){
            String token = null;
            if (request.customerId == null || request.customerId == 0){
                token = servletRequest.getHeader("token");
            }

            TrRetreatTicketResponse response = null;
            if (token != null) {
                response = trainOrderService.retreatTicket(token, request);
            } else {
                response = trainOrderService.retreatTicket(null, request);
            }

            return AjaxResult.success(response);
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 收银台
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/queryByPayOrder")
    public AjaxResult queryByPayOrder(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String token = request.getHeader("token");
        String orderNumber = String.valueOf(map.get("orderNumber"));
        String businessType = String.valueOf(map.get("businessType"));
        Cashier cashier = trainOrderService.queryByPayOrder(token, orderNumber, businessType);
        return AjaxResult.success(cashier);
    }

    /**
     * 微信小程序支付
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/wechatPay")
    public AjaxResult wechatPay(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String token = request.getHeader("token");
        R<Customer> customer;
        try {
            customer = customerService.getLoginCustomerByToken(token);
            String openId = map.get("openId");
            String orderNumber = map.get("orderNumber");
            Long customerId = customer.getData().getCustomerId();

            BigDecimal amount = new BigDecimal(0);
            if (map.get("amount") != null && !map.get("amount").equals("")){
                amount = new BigDecimal(map.get("amount"));
            }

            Map<String, Object> wechat = trainOrderService.wechatPay(customerId, openId, orderNumber, amount);
            if (wechat != null)
                return AjaxResult.success(wechat);
            else
                return AjaxResult.error("支付失败");
        } catch (Exception e) {
            return AjaxResult.expired("登录已过期，请重新登录");
        }
    }

    /**
     * 改签微信小程序支付
     * @param map
     * @return
     */
    @PostMapping("/changeWechatPay")
    public AjaxResult changeWechatPay(@RequestBody Map<String, String> map) {
        String openId = map.get("openId");
        String orderNumber = map.get("orderNumber");

        BigDecimal amount = new BigDecimal(0);
        if (map.get("amount") != null && !map.get("amount").equals("")){
            amount = new BigDecimal(map.get("amount"));
        }

        String type = map.get("type");

        Map<String, Object> wechat;
        try {
            wechat = trainOrderService.changeWechatPay(openId, orderNumber, amount, type);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (wechat != null)
            return AjaxResult.success(wechat);
        else
            return AjaxResult.error("支付失败");
    }

    /**
     * 查询会员火车票订单列表
     * */
    @PostMapping("/trainOrderNum")
    public List<TrainOrder> trainOrderNum(@RequestBody Map<String, Object> map){
        Long customerId = Long.valueOf(map.get("customerId").toString());
        List<TrainOrder> trainOrders;
        try {
            trainOrders = trainOrderService.selectTrainOrderNum(customerId);
        } catch (Exception e){
            return null;
        }

        if (trainOrders != null && trainOrders.size() > 0){
            return trainOrders;
        }
        else {
            return null;
        }
    }

    /**
     * 火车票订单列表（CRM）
     * @param order
     * @return
     */
    @PostMapping("/trainOrder")
    public TableDataInfo trainOrder(@RequestBody TrainCRMOrder order) {
        startPage();
        List<TrainOrderCRM> trainOrderCRMS = trainOrderService.trainOrder(order);
        return getDataTable(trainOrderCRMS);
    }

    /**
     * 火车票订单列表（CRM）
     * @param order
     * @return
     */
    @PostMapping("/orderList")
    public List<TrainOrderCRM> orderList(@RequestBody TrainCRMOrder order) {
        List<TrainOrderCRM> trainOrderCRMS = trainOrderService.trainOrder(order);
        return trainOrderCRMS;
    }

    /**
     * 火车票订单列表
     * */
    @PostMapping("/trainOrderList")
    public AjaxResult trainOrderList(@RequestBody Map<String, Object> map){
        String startDate = null;
        String finishDate = null;
        if (map.get("startDate") != null && !map.get("startDate").equals("") &&
                map.get("finishDate") != null && !map.get("finishDate").equals("")){
            startDate = map.get("startDate").toString();
            finishDate = map.get("finishDate").toString();
        }

        List<TrainOrder> trainOrders = trainOrderService.trainOrderList(startDate, finishDate);
        return AjaxResult.success(trainOrders);
    }

    /**
     * 火车票二维码
     * */
    @PostMapping("/tainCodePay")
    public AjaxResult tainCodePay(HttpServletRequest request, @RequestBody Map<String, String> map) {
        if (map.get("billNo") != null && !map.get("billNo").equals("")){
            String billNo = map.get("billNo");

            BigDecimal amount = new BigDecimal(0);
            if (map.get("amount") != null && !map.get("amount").equals("")){
                amount = new BigDecimal(map.get("amount"));
            }

            String type = map.get("type");

            UnionPayQRCodeResponseApi unionPayQRCodeResponseApi;
            try {
                unionPayQRCodeResponseApi = trainOrderService.tainCodePay(request, billNo, amount, type);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }

            return AjaxResult.success(unionPayQRCodeResponseApi);
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 请求改签
     * @param request
     * @return
     */
    @PostMapping("/trainRequestChange")
    public AjaxResult trainRequestChange(@RequestBody TrTicketChangesRequest request) {
        TrainChangeOrder changeOrder = trainOrderService.trainRequestChange(request);
        if (changeOrder != null)
            return AjaxResult.success(changeOrder);
        else
            return AjaxResult.error("请求改签失败！");
    }

    /**
     * 取消改签
     * @param map
     * @return
     */
    @PostMapping("/trainCancelChange")
    public TrCancelChangeResponse trainCancelChange(@RequestBody Map<String, Object> map) {
        String orderId = String.valueOf(map.get("orderId"));
        TrCancelChangeResponse response = trainOrderService.trainCancelChange(orderId);
        return response;
    }

    /**
     * 改签支付
     * @param map
     * @return
     */
    @PostMapping("/trainRequestChangeQRCode")
    public AjaxResult trainRequestChangeQRCode(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String billNo = String.valueOf(map.get("billNo"));

        BigDecimal amount = new BigDecimal(0);
        if (map.get("amount") != null && !map.get("amount").equals("")){
            amount = new BigDecimal(map.get("amount").toString());
        }

        String type = map.get("type").toString();

        UnionPayQRCodeResponseApi qrCode;
        try {
            qrCode = trainOrderService.trainRequestChangeQRCode(request, billNo, amount, type);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (qrCode != null)
            return AjaxResult.success(qrCode);
        else
            return AjaxResult.error("银联二维码支付码获取失败！");
    }

    @PostMapping("/queryTrainOrderNumber")
    public int queryTrainOrderNumber(@RequestBody Long customerId) {
        return trainOrderService.queryTrainOrderNumber(customerId);
    }

    /**
     * 支付宝支付
     * @param map
     * @return
     */
    @PostMapping("/aliPay")
    public AjaxResult aliPay(@RequestBody Map<String, String> map) {
        if (map.get("orderNumber") != null && !map.get("orderNumber").equals("")) {
            String orderNumber = map.get("orderNumber");
            String aliPay = trainOrderService.aliPay(orderNumber);
            if (aliPay != null && !aliPay.equals(""))
                return AjaxResult.success(aliPay);
            else
                return AjaxResult.error("操作失败！");
        } else {
            return AjaxResult.error("缺少必要参数！");
        }
    }

    /**
     * 火车票银行卡支付
     * @param bankCardPay
     * @return
     * @throws Exception
     */
    @PostMapping("/bankCardPay")
    public AjaxResult bankCardPay(HttpServletRequest request, @RequestBody TrainBankCardPay bankCardPay) {
        String cardPay = null;
        try {
            cardPay = trainOrderService.bankCardPay(request, bankCardPay);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(cardPay);
    }

    /**
     * 改签火车票银行卡支付
     * @param bankCardPay
     * @return
     */
    @PostMapping("/changeBankCardPay")
    public AjaxResult changeBankCardPay(HttpServletRequest request, @RequestBody TrainBankCardPay bankCardPay) {
        String cardPay = null;
        try {
            cardPay = trainOrderService.changeBankCardPay(request, bankCardPay);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(cardPay);
    }

    /**
     * 火车票语音支付
     * @param bankCardPay
     * @return
     */
    @PostMapping("/voice")
    public AjaxResult voice(HttpServletRequest request, @RequestBody TrainBankCardPay bankCardPay) {
        String voice;
        try {
            voice = trainOrderService.voice(request, bankCardPay);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success(voice);
    }

    /**
     * 订单列表
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/orderApp")
    public AjaxResult orderApp(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String token = request.getHeader("token");
        R<Customer> customer = customerService.getLoginCustomerByToken(token);
        String status = String.valueOf(map.get("status"));
        List<TrainOrderApp> orderApps = trainOrderService.orderApp(customer.getData().getCustomerId(), status);
        if (orderApps != null && orderApps.size() > 0)
            return AjaxResult.success(orderApps);
        else
            return AjaxResult.error("未查询到信息");
    }

    /**
     * 行程火车票订单
     * */
    @PostMapping("/journeyTrainOrder")
    public JourneyTrainOrderVo journeyTrainOrder(@RequestBody Map<String, Object> map) {
        Long orderid = Long.valueOf(map.get("orderid").toString());
        JourneyTrainOrderVo journeyTrainOrderVo = trainOrderService.journeyTrainOrder(orderid);
        return journeyTrainOrderVo;
    }

    /**
     * 订单号获取火车票订单信息
     * */
    @PostMapping("/orderNum")
    public TrainOrder orderNum(@RequestBody Map<String, Object> map){
        String orderNum = map.get("orderNum").toString();
        TrainOrder trainOrder = trainOrderService.orderNum(orderNum);
        return trainOrder;
    }

    /**
     * 火车票订单号获取会员信息
     * */
    @PostMapping("/customerByTrainNum")
    public AjaxResult customerByTrainNum(@RequestBody Map<String, Object> map){
        String orderNum = map.get("orderNum").toString();
        CustomerTrain customerTrain = trainOrderService.customerByTrainNum(orderNum);
        return AjaxResult.success(customerTrain);
    }

    /**
     * 获取火车票的待跟进订单
     * @return
     */
    @PostMapping("/trainOrderListThings")
    public List<TrainOrder> orderListThings()
    {
        return trainOrderService.orderListThings();
    }
}
